import { ExportOutlined } from '@ant-design/icons';
import { Button, Card, Descriptions, InputNumber, message, Space } from 'antd';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import * as XLSX from 'xlsx';

class DetailAndExport extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      record: null,
      count: 0,
      exportLoading: false,
      begin: 0,
      end: 0,
    };
  }

  componentDidMount() {
    this.open();
  }

  open = () => {
    const fenceId = this.props.location.query.fenceId;
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/getData',
      payload: {
        url: '/electricfence/getfencedetail',
        fenceId,
      },
      callback: (res: any) => {
        this.setState({ record: res.data });
      },
    });
    dispatch({
      type: 'electricFenceMng/getData',
      payload: {
        url: '/electricfence/getvehiclecount',
        fenceId,
      },
      callback: (res: any) => {
        this.setState({ count: res.data });
      },
    });
  };

  close = () => {
    router.replace(`${self === top ? '' : '/external'}/electricFence/electricFenceMng`);
  };

  handleExport = () => {
    const { dispatch } = this.props;
    this.setState({ exportLoading: true });
    dispatch({
      type: 'http/postData',
      payload: {
        url: '/electricfence/exportfenceofbindvin',
        fenceId: this.state.record.id,
        begin: this.state.begin,
        end: this.state.end,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const ws = XLSX.utils.json_to_sheet(
            res.data.map((e) => ({ vin: e })),
            { skipHeader: false },
          );
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, 'export');
          XLSX.writeFile(wb, 'export.xlsx');
        } else {
          message.error('导出失败');
        }
      },
    }).finally(() => this.setState({ exportLoading: false }));
  };

  render() {
    const { record, count } = this.state;
    return (
      <Card
        title="围栏详情"
        onClose={this.close}
        // closable={false}
        bodyStyle={{ padding: '12px 24px' }}
        width={800}
        extra={
          <Button size="small" onClick={this.close}>
            关闭
          </Button>
        }
      >
        <Descriptions title="围栏信息" column={1}>
          <Descriptions.Item label="围栏编号">{record && record.fenceCode}</Descriptions.Item>
          <Descriptions.Item label="围栏名称">{record && record.fenceName}</Descriptions.Item>
          <Descriptions.Item label="围栏所属组织">{record && record.orgName}</Descriptions.Item>
          {/* <Descriptions.Item label="经销商">{record && record.dealerName}</Descriptions.Item> */}
          {/* <Descriptions.Item label="预警方式">
            {record && record.warningConfigDesc}
          </Descriptions.Item> */}
          <Descriptions.Item label="围栏有效期">
            {record && record.warningBeginDate && record.warningEndDate
              ? `${record.warningBeginDate} ~ ${record.warningEndDate}`
              : '无限制'}
          </Descriptions.Item>

          {record && record.fenceType == 0 ? (
            <>
              <Descriptions.Item
                label="围栏中心点位置"
                contentStyle={{ whiteSpace: 'break-spaces' }}
              >
                {(record && record.circleList && record.circleList[0].fenceCenterAddress) ||
                  (record && record.polygonList && record.polygonList[0].fenceCenterAddress)}
              </Descriptions.Item>
              <Descriptions.Item label="围栏中心点经纬度">
                {(record &&
                  record.circleList &&
                  record.circleList[0] &&
                  `(${record.circleList[0].centerLng},${record.circleList[0].centerLat})`) ||
                  (record &&
                    record.polygonList &&
                    record.polygonList[0] &&
                    `(${record.polygonList[0].centerLng},${record.polygonList[0].centerLat})`)}
              </Descriptions.Item>
              {record && record.circleList && record.circleList[0] ? (
                <Descriptions.Item label="半径范围">
                  {record.circleList[0].radius}米
                </Descriptions.Item>
              ) : null}
            </>
          ) : null}

          {record && record.fenceType == 1 ? (
            <>
              <Descriptions.Item label="省级行政区">
                {record &&
                  record.districtList &&
                  record.districtList[0] &&
                  record.districtList[0].provinceName}
              </Descriptions.Item>
              <Descriptions.Item label="市级行政区">
                {record &&
                  record.districtList &&
                  record.districtList[0] &&
                  record.districtList[0].cityName}
              </Descriptions.Item>
              <Descriptions.Item label="县级行政区">
                {record &&
                  record.districtList &&
                  record.districtList[0] &&
                  record.districtList[0].areaName}
              </Descriptions.Item>
            </>
          ) : null}
        </Descriptions>
        <Descriptions title="车辆信息" column={1}>
          <Descriptions.Item label="已关联车辆">
            <Space>
              <span>{count} 辆</span>
              {count ? (
                <>
                  <Button
                    size="small"
                    icon={<ExportOutlined />}
                    type="primary"
                    onClick={() => this.handleExport()}
                    loading={this.state.exportLoading}
                    disabled={
                      !(
                        this.state.begin <= this.state.end &&
                        this.state.end <= count &&
                        this.state.begin > 0
                      )
                    }
                  >
                    导出
                  </Button>
                  <span>导出第</span>
                  <InputNumber
                    size="small"
                    min={1}
                    max={count}
                    value={this.state.begin || ''}
                    onChange={(begin) => {
                      this.setState({ begin });
                    }}
                  />
                  <span>至</span>
                  <InputNumber
                    size="small"
                    min={this.state.begin}
                    max={count}
                    value={this.state.end && this.state.begin ? this.state.end : ''}
                    onChange={(end) => {
                      this.setState({ end });
                    }}
                  />
                  <span>条数据</span>
                </>
              ) : null}
            </Space>
          </Descriptions.Item>
        </Descriptions>
      </Card>
    );
  }
}

export default connect()(DetailAndExport);
